/*!
  辣笑前端 Copyright (c) 2022 拉销CRM.
  Licensed under the MIT License (MIT), see
  https://www.laxiao.com
*/

/*!
需要引入 toastr 和 sweetalert（swal） 插件，否则将用原始alert提示
*/
;(function(factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports !== 'undefined') {
    module.exports = factory(require('jquery'));
  } else {
    factory(jQuery);
  }
}(function($) {
  'use strict';
  var Laxiao = window.Laxiao || {};
  Laxiao = (function() {
    function Laxiao(element, settings) {
        var _ = this, dataSettings;
        _.defaults = {
            accessibility: true,
            zIndex: 1000
        };
        _.initials = {
            animating: false,
            dragging: false,
        };
        $.extend(_, _.initials);
        _.windowTimer = null;
        dataSettings = $(element).data('laxiao') || {};
        _.options = $.extend({}, _.defaults, settings, dataSettings);
        _.init(true);
    }
    return Laxiao;
  }());

  Laxiao.prototype.pip = function() {
    var _ = this;
    $(document).on('click','a.pip',function () {
      if(!$('div.pip').length){
        _.initPip();
      }
      var _this = $(this);
      _.setPipSize();
      var url = _this.attr('href');
      var title = _this.attr('title');
      if(!title){title = '标题';}
      if(!url){return false;}
      $('body').addClass('stop-scrolling');
      $("div.pip .card .card-header-title").html(title);
      $("div.pip .card .card-body").html('<div class="refresh"></div>');
      $('div.pip').show();
      $.ajax({
        url:url,
        header:{
            'Access-Control-Allow-Origin':'*',
            'Access-Control-Allow-Headers':'X-Requested-With',
            'Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'
        },
        type:'get',
        beforeSend: function (request) {
          request.setRequestHeader("ajax","1");
        },
        success:function(res){
          if(typeof(res) == 'object'){
            console.log(res);
            if(res){
              if(res.status == 1 && res.info){
                _.success(res.info);
              }else if(res.status == 0 && res.info){
                _.error(res.info);
              }
              if(res.url){
                _.redirect(res.url);return false;
              }
            }
          }else{
            $("div.pip .card .card-body").html(res);
          }
        }
      });
      return false;
    });
  };

  Laxiao.prototype.ajax = function() {
    var _ = this;
    $(document).on('click','a.ajax',function () {
      var _this = $(this);
      if(_this.hasClass('confirm')){return false;}    //无confirm才执行
      var url           = _this.attr('href');
      var reload        = _this.hasClass('reload');
      var redirect      = _this.attr('data-ajax-redirect');
      if(!url){return false;}
      $.ajax({
        url:url,
        type:'get',
        beforeSend: function (request) {
          request.setRequestHeader("ajax","1");
        },
        success:function(res){
          //重新加载
          if(reload){
            _.reload();return false;
          }
          if(redirect){
            _.redirect(redirect);return false;
          }
          if(typeof res == 'string'){
            res         = JSON.parse(res);
          }
          try{
            if(typeof res == 'object'){
              if(res.status == 1 && res.info){
                _.success(res.info);
              }else if(res.status == 0 && res.info){
                _.error(res.info);
              }
              if(res.url){
                _.redirect(res.url);return false;
              }
            }
          }catch(err){}
        }
      });
      return false;
    });
  };

  Laxiao.prototype.confirm = function() {
    var _ = this;
    //确认
    $(document).on('click','a.confirm', function() {
      var _this		      = $(this);
      var url           = _this.attr('href');
      var title         = _this.attr('data-confirm-title');
      var ajax          = _this.hasClass('ajax');
      var redirect1     = _this.attr('data-confirm-redirect');
      var redirect2     = _this.attr('data-ajax-redirect');
      var reload        = _this.hasClass('reload');
      title             = title ? title : "确认操作吗?";
      if(!url){return false;}
      if(typeof swal == 'undefind'){
        if(confirm(title)){
          _.redirect(url);return false;
        }
      }else{
        swal({
          title: title,
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: true
        }, function(){
          if(ajax){
            $.ajax({
              url:url,
              type:'get',
              beforeSend: function (request) {
                request.setRequestHeader("ajax","1");
              },
              success:function(res){
                //重新加载
                if(reload){
                  _.reload();return false;
                }
                if(redirect1){
                  _.redirect(redirect1);return false;
                }
                if(redirect2){
                  _.redirect(redirect2);return false;
                }
                if(typeof res == 'string'){
                  res         = JSON.parse(res);
                }
                try{
                  if(typeof res == 'object'){
                    if(res && res.url){
                      _.redirect(res.url);return false;
                    }
                  }
                }catch(err){}
              }
            });
            return false;
          }else{
            _.redirect(url);return false;
          }
        });
      }
      return false;
    });
  };

  Laxiao.prototype.setPipSize = function() {
    var width	= window.innerWidth;
    var width = width > 1200 ? (width-500) + 'px' : (width > 992 ? (width-300) + 'px' : width > 768 ? (width-200) + 'px' : '100%');
    $('.pip .card .card-body').attr('style','height:' + (window.innerHeight - 100) + 'px;width:'+ width +';');
  };

  Laxiao.prototype.initPip = function() {
    var _ = this;
    if(!$('div.pip').length){
      $('body').append('<div class="pip"><div class="card"><div class="card-header"><a class="close" title="关闭 (快捷键：Esc)"></a><h4 class="card-header-title"></h4></div><div class="card-body"></div></div></div>');
    }
    $('div.pip a.close').on('click', function() {
      $('body').removeClass('stop-scrolling');
      $("div.pip .card .card-body").html('');
      $('div.pip').hide(300);
      return false;
    });
    $(window).resize( function (){
      _.setPipSize();
    });
    //Esc关闭pip层
    $(document).on('keydown',function(){
      if(window.event.keyCode == 27){
        $('body').removeClass('stop-scrolling');
        $("div.pip .card .card-body").html('');
        $('div.pip').hide(300);
        return false;
      }
    });
  };

  Laxiao.prototype.form = function() {
    var _ = this;
    //Ajax提交
    $(document).on('submit','form.ajax',function(){
      var _form		      = $(this);
      var isConfirm     = _form.hasClass('confirm');
      var disabled      = _form.hasClass('disabled');
      if(!disabled){
        var url         = _form.attr('action');
        var redirect    = _form.attr('data-ajax-redirect');
        if(isConfirm){
          var title   = _form.attr('data-confirm-title');
          title       = title ? title : "确认提交吗?";
          if((typeof swal) == 'undefined'){
            if(confirm(title)){
              _.submit(_form,url,redirect);
            }
          }else{
            swal({
              title: title,
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              closeOnConfirm: true
            }, function(){
              _.submit(_form,url,redirect);
            });
          }
        }else{
          _.submit(_form,url,redirect);
        }
      }
      return false;
    });
  };

  Laxiao.prototype.submit = function(_form,url,redirect=null){
    var _ = this;
    if(!_form || !url){return false;}
    _form.addClass('disabled');
    url = url.indexOf('?') == -1 ? url + '?_ajax=1' : url + '&_ajax=1';
    $.ajax({
      url:url,
      type:'post',
      data:_form.serialize(),
      beforeSend: function (request) {
        request.setRequestHeader("ajax","1");
      },
      success:function(res){
        if(res){
          if((typeof res) == 'string'){
            res         = JSON.parse(res);
          }
          if(res.status == 0){
            _.error(res.info);
          }else if(res.status == 1){
            _.success(res.info);
            $('div.pip').hide(300);
            if(!redirect && res.url){
              redirect  = res.url;
            }
            if(_form.hasClass('reload')){
              _.reload();
            }else if(redirect){
              _.redirect(redirect);return false;
            }
          }
          _form.removeClass('disabled');
        }
      }
    });
  };

  Laxiao.prototype.getOption = function(option) {
      var _ = this;
      return _.options[option];
  };

  Laxiao.prototype.getLaxiao = function(){
    return this;
  };

  Laxiao.prototype.reload = function(){
    setTimeout(function(){
      window.location.reload();
    },500);
  };

  Laxiao.prototype.redirect = function(url = null){
    if(url){
      setTimeout(function(){
        window.location.href = url;
      },500);
    }
  };

  Laxiao.prototype.success = function(info){
    if(typeof toastr == 'undefined'){
      alert(info);
    }else{
      toastr.clear();
      toastr.success(info);
    }
  };

  Laxiao.prototype.error = function(info){
    if(typeof toastr == 'undefined'){
      alert(info);
    }else{
      toastr.clear();
      toastr.error(info);
    }
  };

  Laxiao.prototype.init = function(creation) {
    var _ = this;
    _.pip();
    _.confirm();
    _.ajax();
    _.form();
  };

  $.fn.laxiao = function() {
    var _ = this,
      opt = arguments[0],
      args = Array.prototype.slice.call(arguments, 1),
      l = _.length,
      i,
      ret;
    for (i = 0; i < l; i++) {
      if (typeof opt == 'object' || typeof opt == 'undefined')
        _[i].laxiao = new Laxiao(_[i], opt);
      else
        ret = _[i].laxiao[opt].apply(_[i].laxiao, args);
      if (typeof ret != 'undefined') return ret;
    }
    return _;
  };
}));

$(document).ready(function() {
	$(document).laxiao();
});